<?php

namespace app\admin\controller;

use app\admin\model\Article;
use app\admin\model\Category as ModelCategory;
use app\admin\model\User;
use app\common\LogService;
use think\facade\Db;
use think\facade\Log;

class Category  extends Base
{
    public function index()
    {
        return view();
    }
    public function list()
    {
        $limit = input('limit');
        $cate_name = input('cate_name');
        $status = input('status');
        $page = input('page', 1);
        $pageSize = input('page_size', 10);
        $list = ModelCategory::list($page, $pageSize);
        if (!empty($cate_name) || $status != '') {
            $list = ModelCategory::order('sort desc');
            if ($status != '') {
                $list->where(['status' => $status]);
            }
            if (!empty($cate_name)) {
                $list->where('cate_name', 'like', "%$cate_name%");
            }
            $list = $list->paginate($limit);
        }
        return success($list);
    }
    public function add()
    {
        $cate = ModelCategory::where(['pid' => 0])->select();
        // 获取分类数据
        return view('add', ['cate' => $cate]);
    }
    public function doAdd()
    {
        $param = input('post.');
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '添加分类',
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        if (@$param['cate_name'] == '') {
            $recordLog(0, '分类名称不能为空');
            return error('分类名称不能为空');
        }
        if (@$param['pid'] == '') {
            $recordLog(0, '分类pid不能为空');
            return error('分类pid不能为空');
        }
        $has = Db::name('category')->where(['pid' => $param['pid'], 'cate_name' => $param['cate_name']])->find();
        if ($has) {
            $recordLog(0, '已存在该分类名称');
            return error('已存在该分类名称');
        }
        if (@$param['icon'] != '' && !file_exists(app()->getRootPath() . '/public' . $param['icon'])) {
            $recordLog(0, '分类图片地址有误');
            return error('分类图片地址有误');
        }
        if ($param['pid'] != 0) {
            unset($param['icon']);
            $cate = Db::name('category')->where(['id' => $param['pid']])->find();
            $recordLog(0, '父分类不存在');
            if (!$cate) return error('父分类不存在');
        }

        $res = ModelCategory::create($param);
        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }
    public function edit($id)
    {
        $category = ModelCategory::find($id);
        $cateList = ModelCategory::where(['pid' => 0])->select();
        return view('edit', ['data' => $category, 'cate' => $cateList]);
    }
    public function doEdit()
    {
        $param = input('post.');
        $target_id = isset($param['id']) ? $param['id'] : '';
        $recordLog = function ($status, $message = '') use ($target_id) {
            LogService::record(
                name: '编辑分类',
                target_id: $target_id,
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        if (isset($param['id']) && $param['id'] == '') {
            $recordLog(0, '分类id不能为空');
            return error('分类id不能为空');
        }
        $cate = Db::name('category')->where(['id' => $param['id']])->find();

        if (!$cate) {
            $recordLog(0, '分类不存在');
            return error('分类不存在');
        }

        if (isset($param['cate_name']) && @$param['cate_name'] != '' && $param['cate_name'] != $cate['cate_name']) {
            $hasName = Db::name('category')->where(['pid' => $cate['pid'], 'cate_name' => $param['cate_name']])->find();
            if ($hasName) {
                $recordLog(0, '分类名称已存在');
                return error('分类名称已存在');
            }
        }
        if (isset($param['icon']) && @$param['icon'] != '' && !file_exists(app()->getRootPath() . '/public' . $param['icon'])) {
            $recordLog(0, '分类图片地址有误');
            return error('分类图片地址有误');
        }
        $res = ModelCategory::where(['id' => $param['id']])->update($param);

        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }
    // 上传图片
    public function uploadIcon()
    {
        $file =  request()->file();
        if (!$file) {
            return error('请上传jpg,png后缀图片');
        }
        try {
            validate(['icon' => 'fileSize:5242880|fileExt:jpg,png,jpeg'])
                ->check($file);
            if (empty($file)) return error();
            $images = \think\facade\Filesystem::disk('images')->putFile('category', $file['icon']);
            if (!$images) return error('图片上传失败');
            $images = '/static/images/' . str_replace('\\', '/', $images);
            LogService::record(
                user_id: $this->uid,
                name: '分类图片上传',
                user_type: 2
            );
            return success($images);
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
    }
    public function del($id)
    {
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '删除分类',
                target_id: $id,
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: 2

            );
        };
        $cate = ModelCategory::where(['id' => $id])->find();
        if (!$cate) {
            $recordLog(0, '分类不存在');
            return error('分类不存在');
        }
        if ($cate['pid'] == 0) {
            $hasChildCate = ModelCategory::where(['pid' => $cate['id']])->find();
            if ($hasChildCate) {
                $recordLog(0, '父分类下还存在子分类');
                return error('父分类下还存在子分类');
            }
        }
        $hasArt = Article::where(['cate_id' => $id, 'status' => 1])->find();
        if ($hasArt) {
            $recordLog(0, '该分类还存在文章，不能删除');
            return error('该分类还存在文章');
        }

        $res = ModelCategory::destroy($id);
        if ($res) {
            $recordLog(1);
            return success();
        }
        $recordLog(0);
        return error();
    }
}
